<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { orderDetailApi, uploadImgApi } from '@/apis/consult'
  import { useUserStore } from '@/sotre/user'
  import type { OrderDetail } from '@/types/consult'
  import { nextTick, ref } from 'vue'
  import roomStatus from './components/room-status.vue'
  import notifyInfo from './components/notify-info.vue'
  // 引入通知消息组件
  import messageInfo from './components/message-info.vue'
  import prescriptionInfo from './components/prescription-info.vue'
  import type { MsgData, MsgItem } from '@/types/room'
  // 引入患者信息组件
  import patientInfo from './components/patient-info.vue'

  // 声明全局 io 变量类型
  declare const io: typeof import('socket.io-client').io

  const store = useUserStore()

  const props = defineProps<{
    orderId: string
    payResult: string
  }>()

  // 1. 处理支付失败
  if (props.payResult === 'false') {
    uni.switchTab({
      url: '/pages/my/index',
    })
  }

  // 2. 建立连接
  const socket = io('https://consult-api.itheima.net', {
    auth: { token: 'Bearer ' + store.token },
    query: { orderId: props.orderId },
    transports: ['websocket', 'polling'],
    timeout: 5000,
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('连接建立成功')
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('出现错误')
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('断开连接')
  })

  // 3. 发送情趣问诊订单详情
  const orderDetail = ref({} as OrderDetail)
  const getOrderDetail = async () => {
    const data = await orderDetailApi(props.orderId)
    console.log('问诊订单详情：', data)
    orderDetail.value = data
  }
  getOrderDetail()

  // 4. 监听订单状态变化
  socket.on('statusChange', getOrderDetail)
  // 4.获取历史消息
  // 消息列表
  const messageList = ref<MsgItem[]>([])
  socket.on('chatMsgList', (res: MsgData) => {
    // 没有返回数据
    if (res.code !== 10000) return
    console.log('--------------历史消息：', res.data)
    // 提取列表数据
    res.data?.forEach(({ items, createTime }) => {
      //
      messageList.value.push({
        id: Date.now().toString(),
        msg: { content: createTime },
        msgType: 31,
      })
      // 追加到消息列表中
      messageList.value.push(...items!)
    })
  })

  // 3. 接收回复消息 - 服务器传颂过来
  socket.on('receiveChatMsg', (message: MsgItem) => {
    // 修改消息为已读
    socket.emit('updateMsgStatus', message.id)
    // 接收到的消息追加到消息列表中
    messageList.value.push(message)
    console.log('--------------接收回复消息：', message)
    nextTick(() => {
      // 滚动到底部
      sp.value = 'item' + (messageList.value.length - 1)
    })
  })

  // 输入框绑定数据与事件
  const iptMessage = ref('')
  const sendMessage = () => {
    socket.emit('sendChatMsg', {
      from: store.userId,
      to: orderDetail.value.docInfo.id,
      msgType: 1,
      msg: {
        content: iptMessage.value,
      },
    })
    iptMessage.value = ''
  }

  // 发送图片信息
  const onImageButtonClick = async () => {
    // 1. 判断当前问诊订单状态
    if (orderDetail.value.status !== 3) {
      return uni.showToast({
        title: '医生不在线',
      })
    }
    // 2. 选择图片
    const res = await uni.chooseImage()
    const fp = res.tempFilePaths[0]
    // 3. 上传图片
    const picture = await uploadImgApi(fp)
    // 4. 发送图片消息 -使用socket.io
    // 7.4 发送图片消息
    socket.emit('sendChatMsg', {
      from: store.userId,
      to: orderDetail.value.docInfo.id,
      msgType: 4,
      msg: { picture },
    })
  }

  // 控制滚动
  const sp = ref('')
</script>

<template>
  <view class="room-page">
    <!-- 问诊订单状态 -->
    <roomStatus
      v-if="orderDetail?.id"
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.countdown"
      :status="orderDetail.status"
    />

    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="sp"
    >
      <view
        class="message-container"
        v-for="(message, i) in messageList"
        :key="message.id"
        :id="'item' + i"
      >
        <!-- 患者信息（21） -->
        <patient-info v-if="message.msgType === 21" :info="message.msg?.consultRecord!" />
        <notifyInfo v-if="message.msgType! >= 31" :type="message.msgType!">{{
          message.msg?.content
        }}</notifyInfo>
        <messageInfo v-if="message.msgType! <= 4" :type="message.msgType!" :info="message" />
        <prescriptionInfo
          v-if="message.msgType === 22"
          :info="message.msg?.prescription!"
        ></prescriptionInfo>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          v-model="iptMessage"
          @confirm="sendMessage"
          :disabled="orderDetail.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="onImageButtonClick">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './index.scss';
</style>
